package someTestExcemple.tcp;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class ServerReaderThread implements Runnable{
    private Socket socket;

    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            DataInputStream dis = new DataInputStream(inputStream);
            while (true) {
                try {
                    System.out.println("客户端" +socket.getRemoteSocketAddress() + "说:"+ dis.readUTF());
                    //群聊转发
                    sendMsgToAllClient("转发"+dis.readUTF());
                   // SocketAddress socketAddress = socket.getRemoteSocketAddress();
                    //System.out.println("客户端地址："+socketAddress);
                } catch (Exception e) {
                    System.out.println("客户端已经断开连接:" + socket.getRemoteSocketAddress());
                    Server1.sockets.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void sendMsgToAllClient(String msg) {
        for (Socket socket : Server1.sockets) {
            try {
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                System.out.println("转发消息失败");
                throw new RuntimeException(e);
            }
        }
    }
}
